package com.fanshilz.flower2025.apps.admin.sysUser.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import com.fanshilz.flower2025.apps.admin.satoken.AdminCurrentUser;
import com.fanshilz.flower2025.apps.admin.satoken.StpAdminUtil;
import com.fanshilz.flower2025.apps.admin.sysUser.req.SysUserChangeUserStatusReq;
import com.fanshilz.flower2025.apps.admin.sysUser.req.SysUserLoginReq;
import com.fanshilz.flower2025.apps.admin.sysUser.req.SysUserSaveOrUpdateReq;
import com.fanshilz.flower2025.apps.admin.sysUser.req.SysUserTableReq;
import com.fanshilz.flower2025.apps.admin.sysUser.resp.CurrentAdminUserResp;
import com.fanshilz.flower2025.apps.admin.sysUser.resp.RouteItemResp;
import com.fanshilz.flower2025.apps.admin.sysUser.resp.SysUserTableDetailResp;
import com.fanshilz.flower2025.business.sys.sysUser.entity.SysUser;
import com.fanshilz.flower2025.business.sys.sysUser.entity.UserStatusEnum;
import com.fanshilz.flower2025.business.sys.sysUser.service.ISysUserService;
import com.fanshilz.flower2025.business.sys.sysUserRole.entity.SysUserRole;
import com.fanshilz.flower2025.business.sys.sysUserRole.service.ISysUserRoleService;
import com.fanshilz.flower2025.framework.exception.CodeException;
import com.fanshilz.flower2025.framework.resp.Resp;
import com.fanshilz.flower2025.framework.resp.TableResp;
import com.fanshilz.flower2025.framework.util.PasswordUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db;
import io.github.linpeilie.Converter;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "系统用户")
@RequestMapping("/admin/sysUser")
@RestController
public class SysUserController {

    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysUserRoleService sysUserRoleService;
    @Resource
    private Converter converter;

    @PostMapping("/remove/{userId}")
    public Resp<Void> remove(@PathVariable Long userId) {
        boolean b = sysUserService.updateById(SysUser.builder()
                .userId(userId)
                .delFlag(true)
                .build());
        Assert.isTrue(b, CodeException::new);
        StpAdminUtil.kickout(userId);
        return Resp.success();
    }

    @PostMapping("/changeUserStatus")
    public Resp<Void> changeUserStatus(@RequestBody @Valid SysUserChangeUserStatusReq req) {
        boolean b = sysUserService.updateById(SysUser.builder()
                .userId(req.getUserId())
                .userStatus(req.getUserStatus() ? UserStatusEnum.OK : UserStatusEnum.INVALID)
                .build());
        Assert.isTrue(b, CodeException::new);
        if (!req.getUserStatus()) {
            StpAdminUtil.kickout(req.getUserId());
        }
        return Resp.success();
    }

    @PostMapping("/saveOrUpdate")
    @Transactional
    public Resp<Void> saveOrUpdate(@RequestBody @Valid SysUserSaveOrUpdateReq req) {
        SysUser su = converter.convert(req, SysUser.class);
        if (ObjUtil.isNull(req.getUserId())) {
            su.setUserUuid("1" + RandomUtil.randomNumbers(5));
            su.setPwdSalt(RandomUtil.randomNumbers(6));
            su.setPwdHash(PasswordUtil.generated(su.getLoginName(), su.getPwdSalt(), su.getPwdTxt()));
        }
        boolean b = sysUserService.saveOrUpdate(su);

        if (ObjUtil.isNotNull(req.getUserId())) {
            // 操作用户角色 删除所有角色 仅在编辑的情况下进行删除老角色关联信息
//        sysUserRoleService.remove(QueryCondition.create(SYS_USER_ROLE.USER_ID, su.getUserId()));
            AdminCurrentUser currentUser = StpAdminUtil.currentUser();
            Db.updateBySql("UPDATE sys_user_role set del_flag = true, update_user_id = ?, update_user_name = ? WHERE user_id = ?", currentUser.getUserId(), currentUser.getUserName(), su.getUserId());
//        Db.updateBatch("", "");
        }

        // 新增所有用户有关角色
        List<SysUserRole> userRoles = req.getUserRoles().stream().distinct()
                .<SysUserRole>map(roleId -> SysUserRole.builder().userId(su.getUserId()).roleId(roleId).build()).toList();
        sysUserRoleService.saveBatch(userRoles);
        Assert.isTrue(b, CodeException::new);

        return Resp.success();
    }

    @PostMapping("/table")
    public Resp<TableResp<SysUserTableDetailResp>> table(@RequestBody @Valid SysUserTableReq req) {
        Page<SysUserTableDetailResp> page = sysUserService.getMapper().paginateWithRelationsAs(Page.of(req.getCurrent(), req.getPageSize(), req.getTotal()),
                QueryWrapper.create(), SysUserTableDetailResp.class);
        return Resp.success(new TableResp<>(page.getRecords(), page.getTotalRow()));
    }

    @PostMapping("/routeList")
    public Resp<List<RouteItemResp>> routeList() {
        return sysUserService.routeList();
    }

    @Operation(summary = "登录")
    @PostMapping("/login")
    public Resp<Void> login(@RequestBody @Valid SysUserLoginReq req) {
        sysUserService.login(req);
        return Resp.success();
    }

    @Operation(summary = "当前用户")
    @PostMapping("/current")
    public Resp<CurrentAdminUserResp> current() {
        AdminCurrentUser currentUser = StpAdminUtil.currentUser();
        CurrentAdminUserResp resp = converter.convert(currentUser, CurrentAdminUserResp.class);
        resp.setUserMobile(PhoneUtil.hideBetween(resp.getUserMobile()).toString());
        resp.setRoles(currentUser.getRoles());
        return Resp.success(resp);
    }

    @Operation(summary = "注销登录")
    @PostMapping("/logout")
    public Resp<Void> logout() {
        StpAdminUtil.logout();
        return Resp.success();
    }

}
